<template>
  <BaseMainSlot ref="BaseMainSlot">
    <template v-slot:searchbox v-if="topitemtypeId==='CONFIG'">
      <div class="seach-box">
        <div v-if="topitemtypeId==='CONFIG'" class="select-box-content">
          <div class="select-box-content-name">设备名称：</div>
          <el-input
            v-model="equipmentName"
            clearable
            placeholder="请输入设备名称"
            @change="query()"
          />
        </div>
        <div v-if="topitemtypeId==='CONFIG'" class="select-box-content">
          <div class="select-box-content-name">设备类型：</div>
          <el-cascader
            v-model="equipmentTypeCode"
            :props="defaultProps"
            :options="equipmentTypeList"
            :show-all-levels="false"
            clearable
            placeholder="请选择所属设备类型"
            @change="query()"
          />
        </div>
        <!-- <div v-if="topitemtypeId==='CONFIG'" class="select-box-content">
          <div class="select-btns table-btns" @click.stop="changeSelect()">
            <i class="el-icon-circle-check"></i>
            <p v-if="activeName==='1'">收起筛选</p>
            <p v-if="activeName===''">展开筛选</p>
          </div>
        </div>-->
      </div>
      <!-- <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
          </template>
        </el-collapse-item>
      </el-collapse>-->
    </template>

    <template v-slot:typenodeslot>
      <SelectButton
        :topitem-select-list="topitemSelectList"
        @topitemtype="topitemtype"
      />
    </template>
    <template v-slot:content>
      <div class="check-item-con">
        <div v-if="topitemtypeId==='CONFIG'" class="tr-sid">
          <div class="sid-head">设备列表</div>
          <div class="sid-tree">
            <Equiplist ref="Equiplist" @selectionChange="selectionChange" />
          </div>
        </div>
        <div :class="topitemtypeId==='CONFIG'?'table-box':'table-box-all'">
          <template v-if="topitemtypeId==='CONFIG'">
            <ActionBar
              :add-active="addActive"
              :del-active="delActive"
              :page-no="152"
              @add="add"
              @del="del"
            />
            <e-table
              ref="tableData"
              rowKey="equipmentCheckItemMapperId"
              :table-data="tableData"
              :table-columns="tableLabel_Config"
              :page="currentPage"
              :size="pageSize"
              :total="totalSize"
              :loading="loading"
              :table-option="tableOption"
              :table-column-sum="topitemtypeId"
              :loadSaveColumnWhenTableChange="loadSavedColumns"
              @sizeChange="changePageSize"
              @pageChange="changeCurrentPage"
              @tableUpdatePlus="mixTableUpdatePlus"
              @handleSelectionChange="handleSelectionChange"
            >
              <template
                v-if="scoped.row.equipmentCheckItemMapperId"
                slot="standardValue"
                slot-scope="scoped"
              >
                <div
                  v-if="scoped.row.checkType==='NUMTYPE'"
                >{{ scoped.row.lowerLimit?'下限:'+scoped.row.lowerLimit+scoped.row.unitName:'' }}{{ scoped.row.upperLimit?'上限:'+scoped.row.upperLimit+scoped.row.unitName:'' }}</div>
                <div v-else>{{ scoped.row.standardValue||'--' }}</div>
              </template>
              <template
                slot="operate"
                v-if="scoped.row.equipmentCode"
                slot-scope="scoped"
              >
                <span
                  v-if="judgePermission(157,'editTem')"
                  class="table-btns-box"
                  @click="edit(scoped.row)"
                >
                  <i class="el-icon-edit-outline"></i>
                  <span>修改</span>
                </span>

                <span
                  v-if="judgePermission(157,'deleteoneTem')"
                  class="table-btns-box table_del_btn"
                  @click="delOne(scoped.row)"
                >
                  <i class="el-icon-delete table_del_btn"></i>
                  <span>删除</span>
                </span>
              </template>
            </e-table>
          </template>
          <template v-else>
            <ActionBar
              :add-active="addActive"
              :del-active="delActive"
              :page-no="152"
              @add="add"
              @del="del"
            />
            <e-table
              ref="tableData"
              rowKey="checkItemModelId"
              :table-data="tableData"
              :table-columns="tableLabel_Temp"
              :page="currentPage"
              :size="pageSize"
              :total="totalSize"
              :loading="loading"
              :table-option="tableOption"
              :table-column-sum="topitemtypeId"
              :loadSaveColumnWhenTableChange="loadSavedColumns"
              @sizeChange="changePageSize"
              @pageChange="changeCurrentPage"
              @tableUpdatePlus="mixTableUpdatePlus"
              @handleSelectionChange="handleSelectionChange"
            >
              <template
                v-if="scoped.row.checkItemModelId"
                slot="checkType"
                slot-scope="scoped"
              >{{ changeCheckType(scoped.row.checkType) }}</template>
              <template slot="unitName" slot-scope="scoped">
                <div
                  v-if="scoped.row.checkType==='NUMTYPE'&&scoped.row.unitName"
                >{{ scoped.row.unitName }}</div>
                <div
                  v-if="scoped.row.checkType==='ENUMTYPE'&&scoped.row.enumContent"
                >{{ scoped.row.enumContent }}</div>
              </template>
              <template
                slot="operate"
                v-if="scoped.row.checkItemModelId"
                slot-scope="scoped"
              >
                <span
                  v-if="judgePermission(157,'editTem')"
                  class="table-btns-box"
                  @click="edit(scoped.row)"
                >
                  <i class="el-icon-edit-outline"></i>
                  <span>修改</span>
                </span>

                <span
                  v-if="judgePermission(157,'deleteoneTem')"
                  class="table-btns-box table_del_btn"
                  @click="delOne(scoped.row)"
                >
                  <i class="el-icon-delete table_del_btn"></i>
                  <span>删除</span>
                </span>
              </template>
            </e-table>
          </template>
        </div>
      </div>
      <AddEditConfigDialog
        ref="addEditConfigDialog"
        :now-equip-object="nowEquipObject"
        :now-chance-stau="nowChanceStau"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditConfigDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
      <AddEditTemplateDialog
        ref="addEditTemplateDialog"
        :now-chance-stau="nowChanceStau"
        :title-text="titleText"
        :edit-object="editObject"
        :show.sync="showAddEditTemplateDialog"
        @closeDialog="closeDialog"
        @cancelDialog="cancel"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import inspectionDataitemApi from "@/api/equip-inspection/inspection-dataitem";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import AddEditConfigDialog from "./components/add-edit-config-dialog.vue";
import AddEditTemplateDialog from "./components/add-edit-template-dialog.vue";
import { mymixin } from "@/utils/mixin";
import SelectButton from "@/components/equipTypeSelectButton/selcetButton.vue";
import equipTypeApi from "@/api/equip-manage/equip-type/index";
import Equiplist from "@/components/EquipList/equiplist-much.vue";
import { mapGetters } from "vuex";
export default {
  name: "InspectionDataitem",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot,
    AddEditConfigDialog,
    AddEditTemplateDialog,
    SelectButton,
    Equiplist,
  },
  mixins: [mymixin],
  data() {
    return {
      loadSavedColumns: true,
      // 控制弹出框显示隐藏
      showAddEditConfigDialog: false,
      // 控制弹出框显示隐藏
      showAddEditTemplateDialog: false,
      //  搜索条件:设备类型
      equipmentTypeCode: "",
      //  搜索条件:设备名称
      equipmentName: "",
      defaultProps: {
        children: "childList",
        value: "equipmentTypeCode",
        label: "equipmentTypeName",
        emitPath: false,
        checkStrictly: true,
      },
      // 关联设备类型
      equipmentTypeList: [],
      checkedIdList: [],
      topitemtypeId: "CONFIG",
      tableTemplateData: [],
      checkTypeList: [
        { id: "TEXTTYPE", name: "文本型" },
        { id: "ENUMTYPE", name: "列表型" },
        { id: "BOOLEANTYPE", name: "是否型" },
        { id: "NUMTYPE", name: "数字型" },
      ],
      // 选中的设备
      nowEquipObject: {},
      topitemSelectList: [
        { id: "CONFIG", name: "设备检查项配置" },
        { id: "TEMPLATE", name: "检查项模板配置" },
      ],
      // 设备检查配置表单展示项
      tableLabel_Config: [
        {
          label: "检查内容",
          param: "checkItemContent",
          show: true,
        },
        {
          label: "检查项名称",
          param: "checkItemName",
          show: true,
        },
        {
          label: "标准值",
          param: "standardValue",
          show: true,
          slotName: "standardValue",
          notSearch: true,
        },
        {
          label: "检查方式",
          param: "accessMethod",
          show: true,
          notSearch: true,
        },
      ],
      // 检查项配置表单展示项
      tableLabel_Temp: [
        {
          label: "检查项模板名称",
          param: "checkItemName",
          show: true,
        },
        {
          label: "检查项类型",
          param: "checkType",
          show: true,
          slotName: "checkType",
          //               <template v-if="scoped.row.checkItemModelId" slot-scope="scoped">
          // {{ changeCheckType(scoped.row.checkType) }}
          //  </template>
          type: "Select", // input Select Checkbox date
          typeObj: {
            // 动态数据和静态数据
            list: [
              { id: "TEXTTYPE", name: "文本型" },
              { id: "ENUMTYPE", name: "列表型" },
              { id: "BOOLEANTYPE", name: "是否型" },
              { id: "NUMTYPE", name: "数字型" },
            ],
            listName: ["name", "id"], // 动态数据和静态数据数组字段名
          },
        },
        {
          label: "检查方式",
          param: "accessMethod",
          show: true,
          notSearch: true,
        },
        {
          label: "单位/选项名称",
          param: "unitName", // enumContent unitName
          show: true,
          slotName: "unitName",
          notSearch: true,
        },
      ],

      tableLabel: [],
      // 表单事件
      tableOption: {
        label: "操作",
        options: [
          {
            label: "操作",
            slotName: "operate",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  created() {
    this.tableLabel[this.topitemtypeId] = [...this.tableLabel_Config];
    this.queryEquipmentType();
  },
  mounted() {},
  methods: {
    query() {
      this.$refs.Equiplist.query(this.equipmentName, this.equipmentTypeCode);
    },
    // 选择设备传出选择的该设备信息
    selectionChange(e) {
      this.nowEquipObject = e;
      this.queryConfigPageList();
    },
    // 检查项类型转换成名字
    changeCheckType(v) {
      var index = this.checkTypeList.findIndex((item) => item.id === v);
      if (index !== -1) {
        return this.checkTypeList[index]["name"];
      }
    },
    // 关联设备类型
    queryEquipmentType() {
      this.loading = false;
      // 获取数据
      let param = {};
      equipTypeApi.queryTree(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data || [];
          this.equipmentTypeList = data;
          this.filterTreeKey(
            this.equipmentTypeList,
            this.defaultProps.children
          );
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 获取点击的分页index
    topitemtype(e) {
      this.tableLabel = [];
      this.topitemtypeId = e;
      this.pageSize = 10;
      this.currentPage = 1;
      this.checkedIdList = [];
      this.$nextTick(() => {
        this.$refs.BaseMainSlot.calculateHeight();
      });

      // if (this.topitemtypeId === 'CONFIG') {
      //   this.$nextTick(()=> {
      //     this.tableLabel[this.topitemtypeId] = this.tableLabel_Config;
      //     // this.$refs.tableData.setCurrentRow()
      //     // this.$refs.tableData.clearSelection()
      //   })
      // }
      // if (this.topitemtypeId === 'TEMPLATE') {
      //   this.$nextTick(()=> {
      //     this.tableLabel[this.topitemtypeId] = this.tableLabel_Temp;
      //     // this.$refs.tableTemplateData.setCurrentRow()
      //     // this.$refs.tableTemplateData.clearSelection()
      //   })
      // }
      // 获取表格数据
      this.queryPageList();
    },
    queryPageList(e) {
      // console.log(this.searchObj, this.topitemtypeId);
      if (this.topitemtypeId === "CONFIG") {
        this.queryConfigPageList(e);
      }
      if (this.topitemtypeId === "TEMPLATE") {
        this.queryTemplatePageList(e);
      }
    },
    // 设备检查项配置
    queryConfigPageList(e) {
      this.loading = false;
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        // equipmentCode: this.nowEquipObject.equipmentCode
      };
      let list = [
        {
          paramName: "equipmentCode",
          value: this.nowEquipObject.equipmentCode,
          sign: "equals",
        },
      ];
      if (e?.checkItemName) {
        list.push({
          paramName: "checkItemName",
          value: e?.checkItemName,
          sign: "like",
        });
      }
      if (e?.checkItemContent) {
        list.push({
          paramName: "checkItemContent",
          value: e?.checkItemContent,
          sign: "like",
        });
      }
      if (sessionStorage.farming) {
        list.push({
          paramName: "farming",
          value: sessionStorage.farming,
          sign: "equals",
        });
      }

      param["condition"] = encodeURI(JSON.stringify(list));
      inspectionDataitemApi.queryConfigPageList(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data;
          this.totalSize = data.total;
          this.tableData = data.list;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    // 检查项模板配置
    queryTemplatePageList(e) {
      // console.log('1111111111')
      this.loading = false;
      // 获取数据
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        // entity: {
        //   organizationNo: sessionStorage.organizationNo
        // }
      };
      let list = [];
      if (e?.checkItemName) {
        list.push({
          paramName: "checkItemName",
          value: e?.checkItemName,
          sign: "like",
        });
      }
      if (e?.checkType) {
        list.push({
          paramName: "checkType",
          value: e?.checkType,
          sign: "like",
        });
      }
      if (sessionStorage.farming) {
        list.push({
          paramName: "farming",
          value: sessionStorage.farming,
          sign: "equals",
        });
      }
      param["condition"] = encodeURI(JSON.stringify(list));
      inspectionDataitemApi.queryTemplatePageList(param).then((res) => {
        this.loading = false;
        if (res.code === 1) {
          let data = res.data;
          this.totalSize = data.total;
          this.tableData = data.list;
          this.addblankmet();

          // let havline = this.tableTemplateData.length % this.pageSize
          // if (this.tableTemplateData.length < this.pageSize) {
          //   if (havline < this.pageSize) {
          //     const remain = this.pageSize - havline;
          //     for (var i = 0; i < remain; i++) {
          //       this.tableTemplateData.push({ 'index': i + this.tableTemplateData.length - 1 });
          //     }
          //   }
          // }
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      if (list.length == 0) {
        this.delActive = false;
        return;
      }

      this.checkedIdList = [];
      let emptyList = [];
      console.log(this.topitemtypeId, list);
      list.forEach((item) => {
        if (this.topitemtypeId === "CONFIG") {
          if (item.equipmentCheckItemMapperId) {
            this.checkedIdList.push(item.equipmentCheckItemMapperId);
          } else {
            emptyList.push(item);
          }
        } else {
          if (item.checkItemModelId) {
            this.checkedIdList.push(item.checkItemModelId);
          } else {
            emptyList.push(item);
          }
        }
      });
      if (this.checkedIdList.length >= 1) {
        this.delActive = true;
      } else {
        this.delActive = false;
        this.$message.warning("不可选择空数据！");
      }

      if (list.length === emptyList.length) {
        this.toggleNoSelection();
      } else {
        this.toggleNoSelection(emptyList);
      }
    },
    // 单个删除
    delOne(data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          if (this.topitemtypeId === "CONFIG") {
            inspectionDataitemApi
              .delList({
                equipmentCheckItemMapperIdList: [
                  data.equipmentCheckItemMapperId,
                ],
              })
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.queryPageList();
                  this.resetActionBar();
                }
              });
          }
          if (this.topitemtypeId === "TEMPLATE") {
            inspectionDataitemApi
              .delTempalteList({
                checkItemModelIdList: [data.checkItemModelId],
              })
              .then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.queryPageList();
                  this.resetActionBar();
                }
              });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 表格删除
    delmessage() {
      if (this.topitemtypeId === "CONFIG") {
        inspectionDataitemApi
          .delList({ equipmentCheckItemMapperIdList: this.checkedIdList })
          .then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
      }
      if (this.topitemtypeId === "TEMPLATE") {
        inspectionDataitemApi
          .delTempalteList({ checkItemModelIdList: this.checkedIdList })
          .then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.queryPageList();
              this.resetActionBar();
            }
          });
      }
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      if (this.topitemtypeId === "CONFIG") {
        this.showAddEditConfigDialog = true;
      } else if (this.topitemtypeId === "TEMPLATE") {
        this.showAddEditTemplateDialog = true;
      }
    },
    // 修改
    edit(row) {
      if (this.topitemtypeId === "CONFIG") {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditConfigDialog = true;
      } else if (this.topitemtypeId === "TEMPLATE") {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditTemplateDialog = true;
      }
    },
    closeDialog() {
      this.showAddEditConfigDialog = false;
      this.showAddEditTemplateDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      this.queryPageList();
    },
    cancel() {
      this.showAddEditConfigDialog = false;
      this.showAddEditTemplateDialog = false;
      this.nowChanceStau = "";
      this.titleText = "";
      this.editObject = {};
      this.addActive = true;
      this.delActive = false;
      this.$refs.tableData.setCurrentRow();
      this.$refs.tableData.clearSelection();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__header {
  max-width: 100% !important;
}
.check-item-con {
  width: 100%;
  max-width: calc(100% - 1px);
  height: 100%;
  display: flex;
  justify-content: center;
  overflow-y: auto;
  padding: 0 0 20px 0;
  box-sizing: border-box;
}
.tr-sid {
  width: 250px;
  height: 100%;
  padding: 0 10px 10px 10px;
  margin-right: 20px;
  background-color: #225768;
  .sid-head {
    width: 100%;
    height: 40px;
    line-height: 40px;
    font-size: 17px;
    text-align: center;
    border-bottom: #fff dashed 1px;
  }
  .sid-tree {
    width: 100%;
    height: calc(100% - 40px);
    overflow-y: auto;
  }
}
.table-box {
  width: calc(100% - 270px);
  max-width: calc(100% - 240px);
  height: 100%;
  position: relative !important;
  > .table {
    padding: 10px 0 10px;
  }
}
.table-box-all {
  width: 100%;
  height: 100%;
}
</style>
